dojo.provide('jetty.Response');

dojo.declare('jetty.Response', null, {
  constructor: function() {
    this.headers      = {};
    this.body         = '';
    this.errorMessage = '';
    this.status       = 200;
    this.location     = '';
    this.contentType  = 'text/html';
    this.encoding     = 'utf-8';
    this.type         = 'response';
  },
  
  error: function(status, message) {
    this.status = status;
    this.errorMessage = message;
    this.type = 'error';
  },
  
  redirect: function(location, status) {
    this.status = status || 302;
    this.location = location;
    this.type = 'redirect';
  }
});

jetty.Response.commit = function(response, servletResponse) {
  for (var header in response.headers) {
    if (response.headers.hasOwnProperty(header)) servletResponse.addHeader(header, response.headers[header]);
  }
  
  servletResponse.setContentType(response.contentType);
  servletResponse.setCharacterEncoding(response.encoding);
  servletResponse.setStatus(response.status);
  servletResponse.setContentLength(response.body.length);
  servletResponse.getOutputStream().print(response.body);
  
  servletResponse.flushBuffer();
  
  switch (response.type) {
    case 'error':
      if (response.errorMessage) servletResponse.sendError(response.status, response.errorMessage);
      else servletResponse.sendError(response.status);
      break;
    case 'redirect':
      servletResponse.sendRedirect(response.location);
      break;
  }
  
};
